package com.wugh.fast.kernel.validator;


import com.alibaba.fastjson.JSON;
import com.wugh.fast.kernel.validator.exception.FastValidationException;

import javax.validation.ConstraintViolation;
import javax.validation.Validation;
import javax.validation.Validator;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * hibernate-validator校验工具类
 * <p>
 * 参考文档：http://docs.jboss.org/hibernate/validator/5.4/reference/en-US/html_single/
 *
 * @author terry
 * @email terry@189.cn
 * @date 2017-03-15 10:50
 */
public class ValidatorUtils {
    private static Validator validator;

    static {
        validator = Validation.buildDefaultValidatorFactory().getValidator();
    }

    /**
     * 校验对象
     *
     * @param object 待校验对象
     * @param groups 待校验的组
     */
    public static void validateEntity(Object object, Class<?>... groups) {
        Set<ConstraintViolation<Object>> constraintViolations = validator.validate(object, groups);
        valid(constraintViolations);
        if (groups.length > 0) {
            validateEntity(object);
        }
    }

    /**
     * 根据在实体类里面定义好的校验规则,单独校验
     *
     * @param clz       实体类class
     * @param fieldName 判断的字段
     * @param value     输入值
     * @param groups    过滤的组
     */
    public static void validValue(Class<?> clz, String fieldName, Object value, Class<?>... groups) {
        Set<? extends ConstraintViolation<?>> constraintViolations = validator.validateValue(clz, fieldName, value, groups);
        valid(constraintViolations);
    }

    private static void valid(Set<? extends ConstraintViolation<?>> constraintViolations) {
        if (!constraintViolations.isEmpty()) {
            List<String> errors = constraintViolations.stream().map(ConstraintViolation::getMessage).collect(Collectors.toList());
            throw new FastValidationException(JSON.toJSONString(errors));
        }
    }
}
